//###############
//FILE : FileMsg.java
//WRITER : Daniel Lowengrub, daniel_i_l, 320687098
//EXERCISE : oop ex3 2011
//DESCRIPTION:
//See below
//###############
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package oop.ex3.protocol.messages;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import oop.ex3.exceptions.InvalidMessageException;

/**
 * Implements the FILE message. Gets a file stream and file length and uses it to send or
 * receive a file.
 * @author daniel
 */
public class FileMsg extends Message {

    private static final String HEADER = "FILE";
    private static final int FLUSH_RATE = 2;
    private DataInputStream _fileInputStream;
    private DataOutputStream _fileOutputStream;
    private long _fileInputLength;

    /**
     * Create a new message.
     */
    public FileMsg() {
        super(HEADER);
    }

    /**
     * Set the stream that will be read from while sending a file.
     * @param inputStream The file input stream.
     */
    public void setFileInputStream(DataInputStream inputStream) {
        _fileInputStream = inputStream;
    }

    /**
     * Set the stream that will written to while receiving a file.
     * @param outputStream The file output stream.
     */
    public void setFileOutputStream(DataOutputStream outputStream) {
        _fileOutputStream = outputStream;
    }

    /**
     * Set the length of the file we're receiving/sending.
     * @param inputLength The input length.
     */
    public void setInputLength(long inputLength) {
        _fileInputLength = inputLength;
    }

    @Override
    protected void sendDetails(DataOutputStream outputStream) throws IOException {
        outputStream.writeLong(_fileInputLength);
        for (int i=0; i<_fileInputLength; ++i) {
            int inputByte = _fileInputStream.read();
            //System.out.println("sending " + inputByte);
            outputStream.write(inputByte);
            if (i % FLUSH_RATE == 0) //force flush so the socket doesn't timeout
                outputStream.flush();
        }
    }

    @Override
    protected void receiveDetails(DataInputStream inputStream) throws IOException, InvalidMessageException {
        long inputLength = inputStream.readLong();
        for (int i=0; i<inputLength; ++i) {
            int inputByte = inputStream.read();
            //System.out.println("receiving " + inputByte);
            _fileOutputStream.write(inputByte);
        }
    }

}
